package com.paishen.peiniwan.module.square;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.frame.ColorEvaluator;
import com.paishen.peiniwan.frame.WebActivity;
import com.paishen.peiniwan.frame.http.entity.Banner;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/1.
 */
public class BannerLayout extends FrameLayout {

    private final List<Banner> dataList = new ArrayList<>();
    private final ViewPager viewPager;
    private final PagerAdapter adapter;
    private final LinearLayout layDots;
    private final LinearLayout.MarginLayoutParams lpDot = new LinearLayout.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    private boolean init;

    public BannerLayout(Context context) {
        this(context, null);
    }

    public BannerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setPadding(0, BaseUtil.dip2px(1), 0, 0);

        viewPager = new ViewPager(context) {
//            @Override
//            public boolean onTouchEvent(MotionEvent ev) {
//                return false;
//            }
        };
        viewPager.setAdapter(adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE / 2;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                if (dataList.size() > 0) {
                    position = position % dataList.size();
                    View remove = container.findViewWithTag(dataList.get(position));
                    container.removeView(remove);
                }
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                if (dataList.size() > 0) {
                    position = position % dataList.size();

                    FrameLayout wrapper = new FrameLayout(container.getContext());
                    ImageView imageView = new ImageView(container.getContext());
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                    Glide.with(container.getContext()).load(dataList.get(position).url).into(imageView);

                    wrapper.addView(imageView);
                    container.addView(wrapper);

                    wrapper.setTag(dataList.get(position));
                    wrapper.setOnClickListener(onBannerClickListener);
                    return wrapper;
                }
                return null;
            }

            private final View.OnClickListener onBannerClickListener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Banner banner = (Banner) v.getTag();
                    if (banner != null && !TextUtils.isEmpty(banner.jump)) {
                        Intent intent = new Intent(v.getContext(), WebActivity.class);
                        intent.putExtra(WebActivity.EXTRA_URL, banner.jump);
                        v.getContext().startActivity(intent);
                    }
                }
            };
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                int currPosition = (position) % dataList.size();
                DotView dotCurr = (DotView) layDots.getChildAt(currPosition);
                if (dotCurr != null) dotCurr.setCurrProgress(1 - positionOffset);

                if (position > 0) {
                    int lastPosition = (position - 1) % dataList.size();
                    DotView dotLast = (DotView) layDots.getChildAt(lastPosition);
                    if (dotLast != null) dotLast.setCurrProgress(0);
                }

                int lastPosition = (position + 1) % dataList.size();
                DotView dotNext = (DotView) layDots.getChildAt(lastPosition);
                if (dotNext != null) dotNext.setCurrProgress(positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        viewPager.setOnTouchListener(new OnTouchListener() {
            private boolean touch = false;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        if (!touch) {
                            touch = true;
                            stopAutoSliding();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        touch = false;
                        startAutoSliding();
                        break;
                }
                return false;
            }
        });

        addView(viewPager);

        layDots = new LinearLayout(context);
        FrameLayout.LayoutParams lpDotsWrapper = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpDotsWrapper.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        lpDotsWrapper.setMargins(0, 0, 0, BaseUtil.dip2px(5));
        layDots.setLayoutParams(lpDotsWrapper);
        addView(layDots);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // For simple implementation, or internal size is always 0.
        // We depend on the container to specify the layout size of
        // our view. We can't really know what it is since we will be
        // adding and removing different arbitrary views and do not
        // want the layout to change as this happens.
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));

        // Children are just made to fill our space.
        int childWidthSize = getMeasuredWidth();
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        int mHeightSize = (int) (MeasureSpec.getSize(widthMeasureSpec) * 23f / 72);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(mHeightSize, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void setData(List<Banner> dataList) {
        if (dataList != null && dataList.size() > 0) {
            if (init) return;
            init = true;

            this.dataList.clear();
            this.dataList.addAll(dataList);
            adapter.notifyDataSetChanged();

            if (dataList.size() > 1) {
                layDots.removeAllViewsInLayout();
                for (int i = 0; i < dataList.size(); i++) {
                    DotView dot = new DotView(getContext());
                    dot.setLayoutParams(lpDot);
                    if (i == 0) dot.setCurrProgress(1);

                    layDots.addView(dot);
                }
                startAutoSliding();
            }
        }
    }

    private final Runnable runAutoSliding = new Runnable() {
        @Override
        public void run() {
            if (viewPager != null) {
                if (dataList.size() > 1) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                }
            }

            startAutoSliding();
        }
    };

    public void startAutoSliding() {
        stopAutoSliding();

        postDelayed(runAutoSliding, 3000);
    }

    public void stopAutoSliding() {
        removeCallbacks(runAutoSliding);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAutoSliding();
    }

    static final class DotView extends View {
        private int mWidth, mHeight;
        private int centerX, centerY;
        private float radius;
        private final Paint paint;

        private final ColorEvaluator colorEvaluator;

        public DotView(Context context) {
            super(context);
            colorEvaluator = new ColorEvaluator();
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            final float scale = getResources().getDisplayMetrics().density;
            int expected = (int) (6 * scale + 0.5f);
            int spacing = (int) (5 * scale + 0.5f);
            setMeasuredDimension(expected + spacing, expected);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            mWidth = w;
            mHeight = h;
            centerX = w / 2;
            centerY = h / 2;
            radius = h * 0.66f / 2;
        }

        private float progress = 0;

        public void setCurrProgress(float progress) {
            if (progress < 0) progress = 0;
            else if (progress > 1) progress = 1;
            this.progress = progress;
            invalidate();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            final int currColor = (int) colorEvaluator.evaluate(progress, 0xffffffff, 0xffb3b3b3);
            paint.setColor(currColor);
            final float currRadius = radius + (mHeight / 2 - radius) * progress;
            canvas.drawCircle(centerX, centerY, currRadius, paint);
        }
    }
}
